package cn.xspace.library.ui.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;

import com.xspace.android.xafcommon.util.LogUtil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.xspace.library.util.BuildCache;
import cn.xspace.library.util.OkHttpManager;
import okhttp3.Response;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/11/30.
 */

public class DownloadPictureService extends IntentService {

    public static String TYPE = "type";
    public static String DOWNLOAD_WELCOME = "welcomeDownload";
    private Context mContext;

    public DownloadPictureService(String name) {
        super(name);
    }

    public DownloadPictureService() {
        super("DownloadPictureService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String type = intent.getStringExtra(TYPE);
        if (DOWNLOAD_WELCOME.equals(type)) {
            //下载欢迎界面
            OkHttpManager.getInstance().downloadFile(BuildCache.getAppConfigBean(mContext).welcomePage.pageSrc)
                    .subscribeOn(Schedulers.io())
                    .doOnNext(new Action1<Response>() {
                        @Override
                        public void call(Response response) {
                            //保存到文件中
                            try {
                                FileOutputStream fileOutputStream = mContext.openFileOutput("welcome.png", MODE_PRIVATE);
                                byte[] bytes = new byte[2048];
                                //循环读取数据
                                int len = 0;
                                while ((len = response.body().byteStream().read(bytes)) != -1) {
                                    fileOutputStream.write(bytes, 0, len);
                                }
                                fileOutputStream.flush();
                                fileOutputStream.flush();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .subscribe(new Action1<Response>() {
                        @Override
                        public void call(Response response) {
                            LogUtil.d("wubaojie>>>call: 下载成功");
                        }
                    });
        }
    }
}
